package com.xq.tmall.agu.ferign;

import com.xq.tmall.entity.Stock;
import com.xq.tmall.entity.WebPage;
import com.xq.tmall.util.IpFerginUtil;
import com.xq.tmall.util.SpringContextUtil;
import com.xq.tmall.util.TradingDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 抓取竞价量-竞价金额-当前竞价
 **/
@Slf4j
public class FetchBidStockSpider extends AbstractFetchStockSpider<Stock> {

    private final String[] stockCodes;

    public FetchBidStockSpider(String[] stockCodes) {
        this.stockCodes = stockCodes;
        initSpiderConfig();
    }

    private void initSpiderConfig() {
        StringBuilder queryStr = new StringBuilder();
        IpFerginUtil ipFerginUtil = SpringContextUtil.getBean(IpFerginUtil.class);

        for (String code : stockCodes) {
            String resultCode = StockSpider.formatStockCode(code);
            if (null != resultCode) {
                queryStr.append(resultCode).append(",");
            }
        }

        String queryCode = queryStr.toString().replaceAll(",$", "");
        this.pageUrl = String.format("http://qt.gtimg.cn/q=%s", queryCode);
        this.timeOut = 8000;
        this.ignoreContentType = true;
        this.method = Connection.Method.GET;
        this.cookie = ipFerginUtil.getRedisCookies();
        this.useAgent = ipFerginUtil.getUseAgent();
        this.proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(
                        ipFerginUtil.getRedisIp(),
                        Integer.parseInt(ipFerginUtil.getRedisPort())
                )
        );
    }

    @Override
    protected List<Stock> parsePage(WebPage webPage) throws Exception {
        List<Stock> stockList = new ArrayList<>();
        String content = webPage.getDocument().text();
        List<String> rows = Arrays.asList(content.split(";"));

        for (String row : rows) {
            try {
                // 清理无效字符
                String cleanRow = row.replaceAll("v_.*=|\"", "");
                if (cleanRow.isEmpty()) continue;

                String[] item = cleanRow.split("~");
                if (item.length < 50) {
                    log.warn("Invalid data row: {}", cleanRow);
                    continue;
                }
                Stock stock = new Stock();
                stock.setCode(item[2]);
                stock.setYesterdayPrice(Double.parseDouble(item[4]));
                String targetField = null;
                for (String field : item) {
                    if (field.contains("/")) {  // 目标子串由/分隔
                        targetField = field;
                        break;  // 假设只有一个这样的字段，找到后退出循环
                    }
                }

                // 步骤4：校验并拆分目标子串
                if (targetField != null) {
                    String[] parts = targetField.split("/");
                    if (parts.length == 3) {
                        try {
                            double price = Double.parseDouble(parts[0]);    // 19.99
                            double volume = Integer.parseInt(parts[1]);        // 6542
                            double amount = Double.parseDouble(parts[2]);   // 13077458
                            stock.setPrice(price);
                            stock.setBiddingVolume(volume);
                            stock.setBidPrice(amount);
                        } catch (NumberFormatException e) {
                           log.info("字段格式错误，无法转换为数值：" + e.getMessage());
                        }
                    } else {
                        log.info("目标子串格式错误，需包含3个/分隔的值");
                    }
                } else {
                    log.info("未找到目标子串（格式如xxx/xxx/xxx）");
                }
                stock.setPriceDate(Long.valueOf(TradingDateUtil.getDateTime()));
                stockList.add(stock);
            } catch (Exception e) {
                log.error("Error parsing row: {}", row, e);
            }
        }
        return stockList;
    }
}
